<template>
  <!--  课程表-->
  <div class="table-wrapper">
    <div class="table-container">
      <table>
        <thead>
        <tr>
          <th>时间</th>
          <th v-for="(weekNum, weekIndex) in weeks" :key="weekIndex"> {{ '周' + digital2Chinese(weekNum, 'week') }}
          </th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(courseNum, courseIndex) in coursesLen" :key="courseIndex">

          <td>
            <p>{{ '第' + digital2Chinese(courseNum,'') + "节" }}</p>
            <p class="period">{{ classTableData.period[courseIndex] }}</p>
          </td>

          <td v-for="(weekNum, weekIndex) in weeks" :key="weekIndex">
            <el-button
                v-if="fieldCharacter(weekIndex, courseIndex)==='+'"
                style="font-size: 17px"
                type="text"
                @click="addCourseTime(weekIndex+1,courseNum)"
            >+
            </el-button>
            <div v-else>{{ fieldCharacter(weekIndex, courseIndex) }}</div>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
  <!--  选择教学楼和教室-->
  <el-form :model="classroomForm" label-width="120px" style="padding-top: 50px" ref="classroomForm" :rules="this.rules">
    <el-form-item label="教学楼" prop="building">
      <el-select
          v-model="classroomForm.building"
          placeholder="请选择"
          @change="onBuildingChange">
        <el-option v-for="item in this.classroomForm.buildingList"
                   :key="item.buildingId"
                   :label="item.buildingName"
                   :value="item.buildingId">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="教室" prop="classroom">
      <el-select v-model="classroomForm.classroom" placeholder="请选择">
        <el-option
            v-for="item of this.classroomForm.classroomList"
            :key="item.classroomId"
            :label="item.classroomName"
            :value="item.classroomId"
        >
        </el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <span class="dialog-footer">
            <el-button style="margin-left: 175px" type="primary" @click="getCourseInfo">切 换</el-button>
  </span>

  <!--  已选课程时间的编辑-->
  <el-form  label-width="120px" style="padding-top: 50px">
    <el-form-item label="已选时间：">
      <div v-for="item in chosenTime" style="width: 100%">
        第{{item.startTime}}节-第{{item.endTime}}节 教室：{{item.room}}
        <el-button type="text" @click="deleteItem(item)">×</el-button>
      </div>
    </el-form-item>

  </el-form>
  <span class="dialog-footer">
    <el-button style="margin-left: 100px" type="primary" @click="this.$router.back()">取 消</el-button>
    <el-button style="margin-left: 50px" type="primary" @click="SubmitForm">保 存</el-button>
  </span>

  <!--  添加课程时间-->
  <el-dialog v-model="showCourseDialog" title="添加时间" width="30%">
    <el-form label-width="120px" :rules="rules" :model="courseTimeForm" ref="courseTimeForm">
      <el-form-item label="开始时间">
        {{ '周' + digital2Chinese(this.courseTimeForm.start.weekday, 'week') }}
        {{ '第' + digital2Chinese(this.courseTimeForm.start.courseNum, '') + "节" }}
      </el-form-item>
      <el-form-item label="结束时间" prop="end.courseNum">
        <el-select v-model="this.courseTimeForm.end.courseNum" placeholder="请选择">
          <el-option
              v-for="item in this.courseTimeForm.options"
              :key="item"
              :label=" '第' + digital2Chinese(item,'') + '节' "
              :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
          <span class="dialog-footer">
            <el-button @click="showCourseDialog = false">取 消</el-button>
            <el-button type="primary" @click="saveCourseForm">确 定</el-button>
          </span>
    </template>
  </el-dialog>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "TimePlace",
  data() {
    return {
      courseSerialNumber:null,
      // 规则集
      rules:{
        'end.courseNum':[{required:true,message:'请选择结束时间',trigger:'blur'}],
        building:[{required:true,message:'请选择教学楼',trigger:'blur'}],
        classroom:[{required:true,message:'请选择教室',trigger:'blur'}],
      },
      // 课程表相关
      weeks: [], //周集合
      coursesLen: 13, //最大课节数
      CourseData: [
        // {
        //       courseSerialNumber:110,
        //       courseNumber:111,
        //       courseName:"ggg",
        //       schoolId:1,
        //       courseCredit:1.0,
        //       coursePeriod:1.0,
        //       workNumber:"222000",
        //       courseDesc:"1",
        //       courseCapacity:3,
        //       courseEnrollment:3,
        //       majorId:11,
        //       flag:true,
        //       status:0,
        //       start:1,
        //       end:3,
        //       weekday:2,
        //       building:"三教",
        //       classroom:"3104",
        //       kxzy:"1@100@101@102@103",
        //       termId:1
        //     },

      ],
      classTableData: {
        period: [], //时间段
        weekCourse: [
          {
            'week': 1,
            'courses': [
              // {'index': 1, 'title': '物理'},
              // {'index': 3, 'title': '语文'}
            ]
          },
          {
            'week': 2,
            'courses': [
            ]
          },
          {
            'week': 3,
            'courses': [
            ]
          },
          {
            'week': 4,
            'courses': [
            ]
          },
          {
            'week': 5,
            'courses': [
            ]
          },
          {
            'week': 6,
            'courses': []
          },
          {
            'week': 7,
            'courses': []
          },
        ]
      },
      // 表单数据相关
      classroomForm: {
        buildingList:[
          {
            buildingId:'1',
            buildingName:'第三教学楼'
          },
          {
            buildingId: '2',
            buildingName: '光华楼'
          }
        ],
        classroomList:[
          {
            // classroomId:1,
            // classroomName:'3104',
            // buildingName:'三教',
            // capacity:40
          }
        ],
        building:null,
        classroom:null
      },
      courseTimeForm: {
        start: {
          weekday: 0,
          courseNum: 0
        },
        end: {
          optionEnd: 14,
          courseNum: null
        },
        options: []
      },
      chosenTime: [
        {
          courseSerialNumber:null,
          classroom:null,
          building:'',
          start:null,
          end:null,
          weekday:null
        }
      ],
      showCourseDialog: false
    }

  },
  created() {
    this.courseSerialNumber=this.$route.query.courseSerialNumber
    console.log(JSON.stringify(this.courseSerialNumber))
    this.updateData();
    this.courseReformat();
    this.initWeekCourses();
    this.getChosenTime();
    this.getBuildingList();
  },
  methods: {
    /**
     * 对数据进行排序
     */
    updateData() {
      /* 将数据按从周日到周六排序 */
      this.classTableData.weekCourse.sort((a, b) => {
        return a.week - b.week;
      });

      /* 将数据按从第一节到第n节排序 */
      for (let v of this.classTableData.weekCourse) {
        for (let k in v) {
          if (k === 'courses') {
            v[k].sort((a, b) => {
              return a.index - b.index;
            });
          }
        }
      }

      // console.log(JSON.stringify(this.classTableData.weekCourse));
    },
    /**
     * 计算周数据及课节数
     */
    initWeekCourses() {
      const that = this;
      this.weeks = []; //周集合
      this.coursesLen = 13; //最大的课节数

      this.weeks = this.classTableData.weekCourse.map((item, index) => {
        for (let k in item) {
          if (k === 'courses') {
            let maxCoursesLen = 0;
            /* 取出一周中最大的课节数及当天的最大课节数 */
            for (let j of item[k]) {
              j.index > that.coursesLen && (that.coursesLen = j.index); //取所有一周里最大课节值
              j.index > maxCoursesLen && (maxCoursesLen = j.index); //取当天最大课节值
            }

            for (let i = 0; i < maxCoursesLen; i++) { //以最大课节值为终点遍历当天课节
              if (!item[k][i] || item[k][i].index !== (i + 1)) { //如果下标课节不存在或着与循环的下标不匹配
                item[k].splice(i, 0, ''); //填充空课节
              }
            }

          }
        }
        return item.week;
      });
      // console.log(JSON.stringify(this.classTableData.weekCourse));
    },

    /**
     * 处理格子数据，有数据则显示在表中，无数据转换为字符串'-'
     * @param {Number} weekIndex 周几对应的下标
     * @param {Number} courseIndex 第几节课对应的下标
     * @returns {String} 返回对应的字符
     */
    fieldCharacter(weekIndex, courseIndex) {
      if (
          this.classTableData.weekCourse[weekIndex]
          &&
          this.classTableData.weekCourse[weekIndex].courses[courseIndex]
          &&
          this.classTableData.weekCourse[weekIndex].courses[courseIndex].index === courseIndex + 1
      ) {
        return this.classTableData.weekCourse[weekIndex].courses[courseIndex].title;
      }
      return '+';
    },


    /**
     * 数字转中文
     * @param {Number} num 需要转换的数字
     * @param {string} identifier 标识符
     * @returns {String} 转换后的中文
     */
    digital2Chinese(num, identifier) {
      const character = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三'];
      return identifier === 'week' && (num === 0 || num === 7) ? '日' : character[num];
    },
    courseReformat() {
      for (let courseIndex of this.CourseData) {
        console.log(courseIndex);
        for (let i = (Number(courseIndex.start)); i <= Number(courseIndex.end); i++) {
          console.log(i)
          for (let j of this.classTableData.weekCourse) {
            if (j.week === Number(courseIndex.weekday)) {
              let newCourse = {
                'index': i,
                'title': courseIndex.courseName
              }
              j.courses.push(newCourse)
              console.log(JSON.stringify(j.courses))
            }
          }
        }
      }
      console.log(JSON.stringify(this.classTableData.weekCourse));
    },
    getChosenTime(){
      this.chosenTime=[]
      request.get("http://124.70.179.188:8082/course/findTAPByCourseId?courseId="+this.courseSerialNumber).then(res => {
        this.chosenTime=res.data
      })
      console.log(JSON.stringify(this.chosenTime))
    },
    deleteItem(item){
      // 现有课程的删除
      for(let i of this.chosenTime){
          if(i.start===item.start&&i.weekday===item.weekday){
            let deleted=this.chosenTime.splice(Number(i),1)
            console.log(JSON.stringify(deleted))
            this.getChosenTime()
          }
        }
      console.log(JSON.stringify(this.chosenTime))
    },
    saveCourseForm(){
      this.$refs['courseTimeForm'].validate((valid) => {
        console.log("valid:"+valid)
        if (!valid) {
          return false;
        }
        if(!this.classroomForm.classroom){
          this.$alert("请先选择教室！")
          this.showCourseDialog = false
          return false;
        }
        let newCourseTime={
          classroom: this.classroomForm.classroom,//DONE:这里应当是当前所在房间
          start: this.courseTimeForm.start.courseNum,
          end: this.courseTimeForm.end.courseNum,
          weekday: this.courseTimeForm.start.weekday,
        };
        console.log(JSON.stringify(newCourseTime))
        this.chosenTime.push(newCourseTime)
        this.showCourseDialog = false
      });
    },
    addCourseTime(weekIndex, courseNum) {
      this.courseTimeForm.start.weekday = weekIndex
      this.courseTimeForm.start.courseNum = courseNum
      this.courseTimeForm.end.optionEnd = this.coursesLen + 1
      this.courseTimeForm.options = []
      this.courseTimeForm.end.courseNum = null
      this.showCourseDialog = true
      console.log(weekIndex, courseNum)

      for (let i of this.classTableData.weekCourse) {
        if (i.week === weekIndex) {
          for (let j of i.courses) {
            if (j.index > courseNum && j.index < this.courseTimeForm.end.optionEnd) {
              this.courseTimeForm.end.optionEnd = j.index
            }
          }
        }
      }
      for (let index = courseNum; index < this.courseTimeForm.end.optionEnd; index++) {
        this.courseTimeForm.options.push(index)
      }
      console.log("the nearest end is:" + this.courseTimeForm.end.optionEnd)
      console.log("options:" + this.courseTimeForm.options)
    },
    //教学楼&教室联动列表
    getBuildingList() {
      request.get("http://124.70.179.188:8082/place/BuildingList").then(res => {
        this.classroomForm.buildingList=res.data
        console.log('BUILDINGS:'+JSON.stringify(res))
      })
    },
    onBuildingChange(building) {
      this.classroomForm.classroom = ""
      this.getClassroomList(building)
    },
    getClassroomList(building) {
      this.$refs["classroomForm"].validate((valid) => {
        if (valid) {
          request.get("http://124.70.179.188:8082/place/classroomList?buildingId=" + building).then(res => {
            if (res.code === 0) {
              this.classroomForm.classroomList = res.data
              console.log('classroomList:'+JSON.stringify(res))
            }
          })
        }
      })

    },
    getCourseInfo(){
      request.get("http://124.70.179.188:8082/course/schedule?buildingId="+this.classroomForm.building+"&classroomId="+this.classroomForm.classroom).then(res => {
        this.CourseData=res.data
        console.log('courseInfo:'+JSON.stringify(res))
      })
    },
    //提交总表单
    SubmitForm(){
      let successful=false
      request.post("submitWholeFormUrl",this.chosenTime).then(res => {
        if(res.data.code===0){
          this.$message.success('更新成功！')
          successful=true
        }  else {
          this.$message.error('更新失败！')
        }
      })
      if(successful){
        this.$router.back()
      }
    }
  }
};
</script>

<style scoped>

.table-wrapper {
  width: 60%;
  height: 80%;
  float: left;
  overflow: auto;
}

.table-container {
  margin: 7px;
}

table {
  table-layout: fixed;
  width: 100%;
}

thead {
  background-color: #67a1ff;
}

th {
  color: #fff;
  line-height: 17px;
  font-weight: normal;
}


tbody {
  background-color: #eaf2ff;
}

td {
  color: #677998;
  line-height: 12px;
}


th,
td {
  width: 60px;
  padding: 12px 2px;
  font-size: 12px;
  text-align: center;
}

tr td:first-child {
  color: #333;

}

.period {
  font-size: 8px;
}

</style>

